<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称">
          <el-input v-model="listQuery.feeRuleName" clearable class="filter-item" placeholder="规则名称"/>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button
          v-hasPermi="['admin:parkStaticRule:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <el-table-column align="center" label="规则id" prop="id" />
      <el-table-column align="center" label="规则名称" prop="feeRuleName" />
      <el-table-column align="center" label="规则类型" prop="typeStr" />
      <el-table-column align="center" label="创建时间" prop="createTimeStr"/>
      <el-table-column align="center" label="修改时间" prop="updateTimeStr"/>
      <el-table-column align="center" label="机构" prop="departmentName"/>
      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:parkStaticRule:update']"
            type="primary"
            size="small"
            @click="handleEdit(scope.row)">编辑</el-button>
         <el-button
            v-hasPermi="['admin:parkStaticRule:delete']"
            type="primary"
            size="small"
            @click="handleDelete(scope.row.feeRuleName, scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" :title="dialogFormType===1?'添加收费规则':'修改收费规则'" width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="170px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="规则类型" prop="type">
              <el-select :disabled="dialogFormType!==1" v-model="form.type" placeholder="请选择规则类型">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="规则名称" prop="feeRuleName">
              <el-input v-model="form.feeRuleName"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="机构" prop="departmentId">
              <el-select v-model="form.departmentId" :disabled="dialogFormType === 2" placeholder="请选择">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
          </el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="车辆驶离宽限期(分钟)" prop="gracePeriod">
              <el-input v-model="form.gracePeriod" clearable placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="单日收费封顶" prop="dayMaxAmount">
              <el-input v-model="form.dayMaxAmount"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="封顶类型" prop="dayMaxType">
              <el-radio-group v-model="form.dayMaxType">
                <el-radio :label="1">按自然日封顶</el-radio>
                <el-radio :label="2">按24小时封顶</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="特别提醒" prop="warning">
              <el-input v-model="form.warning" type="textarea" clearable placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="收费说明" prop="feeDesc">
              <el-input v-model="form.feeDesc" clearable type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(ruleItem,index) in form.ruleInfoList" :gutter="20" :key="ruleItem.id">
          <el-col :span="4">
            <el-form-item
              :prop="'ruleInfoList.' + index + '.startTime'"
              :rules="{
                required: true, message: '开始时间不能为空', trigger: 'blur'
              }"
              label="时段"
              label-width="50px">
              <el-time-select v-model="ruleItem.startTime" :picker-options="{start:'00:00', step:'00:30', end:'24:00'}" style="width: 7vw;" placeholder="选择"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              :prop="'ruleInfoList.' + index + '.endTime'"
              :rules="{
                required: true, message: '结束时间不能为空', trigger: 'blur'
              }"
              label="至"
              label-width="50px">
              <el-time-select v-model="ruleItem.endTime" :picker-options="{start:'00:00', step:'00:30', end:'24:00'}" style="max-width: 7vw" placeholder="选择"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              :prop="'ruleInfoList.' + index + '.feeWeekId'"
              :rules="{
                required: true, message: '星期类型不能为空', trigger: 'blur'
              }"
              label="星期类型"
              label-width="80px">
              <el-select v-model="ruleItem.feeWeekId" placeholder="请选择">
                <el-option
                  v-for="feeWeek in feeWeekList"
                  :key="feeWeek.id"
                  :label="feeWeek.feeWeekName"
                  :value="Number(feeWeek.id)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="" prop="type" label-width="0px">
              <el-radio-group v-model="ruleItem.type" @change="handleTypeChange(index)($event)">
                <el-radio :label="1">按次收费</el-radio>
                <el-radio :label="2">免费</el-radio>
                <el-radio :label="3">阶梯计时收费</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button v-if="index===form.ruleInfoList.length-1" @click="addRuleInfo">+</el-button>
            <el-button v-if="form.ruleInfoList.length > 1" @click="removeLast(index)">-</el-button>
          </el-col>
          <el-col v-if="ruleItem.type==1" :span="24" style="border:1px solid #ff0000;padding-top: 20px;margin-bottom: 20px;">
            <el-row>
              <el-col :span="24">
                <el-form-item
                  :prop="'ruleInfoList.' + index + '.timeMaxAmount'"
                  :rules="{
                    required: true, message: '收费金额不能为空', trigger: 'blur'
                  }"
                  label="收费"
                  label-width="100px">
                  <el-input
                    v-model="ruleItem.timeMaxAmount"
                    style="width: 200px;"
                    placeholder="请输入内容"
                    onkeyup="value=value.replace(/[^\d\.]/g,'')">
                    <template slot="prepend">￥</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  :prop="'ruleInfoList.' + index + '.freeMinutes'"
                  :rules="{
                    required: true, message: '时间不能为空', trigger: 'blur'
                  }"
                  label="免费时长"
                  label-width="100px">
                  <el-input
                    v-model="ruleItem.freeMinutes"
                    style="width: 200px;"
                    placeholder="请输入内容"
                    onkeyup="value=value.replace(/[^\d\.]/g,'')"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label-width="80px">
                  <el-checkbox v-model="ruleItem.crossCancelFirst" :true-label="1" :false-label="0">跨段收费免费时长不能享受</el-checkbox>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col v-if="ruleItem.type==3" :span="24" style="border:1px solid #ff0000;padding-top: 20px;margin-bottom: 20px;">
            <el-row>
              <el-col v-for="(ladder, j) in ruleItem.ladders" :key="j" :span="24">
                <el-row>
                  <el-col v-if="j===0" :span="4">
                    <el-form-item
                      :prop="'ruleInfoList.' + index + '.ladders.'+j+'.span'"
                      :rules="{
                        required: true, message: '时长不能为空', trigger: 'blur'
                      }"
                      label="首停时长"
                      label-width="100px">
                      <el-input v-model="ladder.span" type="number" min="0" step="15" max="600" onkeyup="value=value.replace(/[^\d\.]/g,'')" oninput="if(value>600)value=600"/>
                    </el-form-item>
                  </el-col>
                  <el-col v-else-if="j===ruleItem.ladders.length-1" :span="4">
                    <el-form-item
                      label="最后到时段结束"
                      label-width="150px">
                      <!-- <el-input :inline="true" v-model="ladder.price" type="text" min="0" max="1000" onkeyup="value=value.replace(/[^\d\.]/g,'')" oninput="if(value>1000)value=1000">
                        <template slot="prepend">￥</template>
                      </el-input> -->
                    </el-form-item>
                  </el-col>
                  <el-col v-else :span="4">
                    <el-form-item
                      :key="j"
                      :prop="'ruleInfoList.' + index + '.ladders.'+j+'.span'"
                      :rules="{
                        required: true, message: '时长不能为空', trigger: 'blur'
                      }"
                      label="之后"
                      label-width="100px">
                      <el-input v-model="ladder.span" type="number" min="0" step="15" max="600" onkeyup="value=value.replace(/[^\d\.]/g,'')" oninput="if(value>600)value=600"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item
                      :prop="'ruleInfoList.' + index + '.ladders.'+j+'.price'"
                      :rules="{
                        required: true, message: '收费不能为空', trigger: 'blur'
                      }"
                      :label="(j===ruleItem.ladders.length-1)?'收费':'分钟 收费'"
                      label-width="90px">
                      <el-input :inline="true" v-model="ladder.price" type="text" min="0" max="1000" onkeyup="value=value.replace(/[^\d\.]/g,'')" oninput="if(value>1000)value=1000">
                        <template slot="prepend">￥</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item
                      :prop="'ruleInfoList.' + index + '.ladders.'+j+'.unit'"
                      :rules="{
                        required: true, message: '时间不能为空', trigger: 'blur'
                      }"
                      label="/"
                      label-width="30px">
                      <el-input v-model="ladder.unit" type="number" min="0" step="15" max="600" oninput="if(value>600)value=600">
                        <template slot="append">分钟</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item
                      v-if="j==0"
                      :prop="'ruleInfoList.' + index + '.freeMinutes'"
                      :rules="{
                        required: true, message: '时间不能为空', trigger: 'blur'
                      }"
                      label="免费时长"
                      label-width="100px">
                      <el-input
                        v-model="ruleItem.freeMinutes"
                        placeholder="请输入"
                        onkeyup="value=value.replace(/[^\d\.]/g,'')"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-button v-if="j ===(ruleItem.ladders.length-2)" style="margin-left: 6px;" @click="addLadder(ruleItem.ladders)">+</el-button>
                    <el-button v-if="(j === ruleItem.ladders.length-2) && j > 0" @click="removeLadder(ruleItem.ladders)">-</el-button>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="24">
                <el-form-item label-width="80px">
                  <el-checkbox v-model="ruleItem.crossCancelFirst" :true-label="1" :false-label="0">跨段收费取消首停</el-checkbox>
                </el-form-item>
              </el-col>


            </el-row>

          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, deleteTempRule, getAllWeeks, getTempRule, createTempRule, updateTempRule } from '@/api/tempRule'
import { getDepartmentList } from '@/api/base'
import { getData, } from '@/api/system/dictionary'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  components: { Pagination },
  data() {
    return {
      typeOptions:[],//规则类型
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      dialogFormVisible: false,
      dialogFormType: 1,
      form: {
        ruleInfoList: [
          { type: 1, ladders: [{}, {}] }
        ]
      },
      rules: {
        type: [{ required: true, message: '请选择规则类型', trigger: 'blur' }],
        feeRuleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构', trigger: 'blur' }],
        gracePeriod: [{ required: true, message: '请输入车辆驶离宽限期', trigger: 'blur' }],
        dayMaxType: [{ required: true, message: '请选择封顶类型', trigger: 'change' }],
      },
      departmentList: [],
      feeWeekList: []
    }
  },
  created() {
    this.getList()
    this.getDepartmentList()
    this.getWeekTypeList()
		this.getData()
  },
  methods: {
		async getData(){//规则类型
			let res = await getData('EFeeRuleType')
			let list = res.data || []
			this.typeOptions = [...list]
		},
    // 规则类型变化
    handleTypeChange(i) {
      return (val) => {
        let form = {...this.form}
        // if (val === 2) {
        //   form.ruleInfoList[i].crossCancelFirst = 0
        //   form.ruleInfoList[i].freeMinutes = null
        //   form.ruleInfoList[i].timeMaxAmount = null
        // }
        if (val === 3) {
          if (form.ruleInfoList[i].ladders.length === 0) {
            form.ruleInfoList[i].ladders = [{}, {}]
          }
        }
        this.form = {...form}
        this.$forceUpdate();
      }
    },
    // 阶梯时段添加
    addLadder(ladders) {
      ladders.splice(ladders.length - 1, 0, {})
    },
    // 阶梯时段删除
    removeLadder(ladders) {
      ladders.splice(ladders.length - 2, 1)
    },
    // 添加时段规则
    addRuleInfo() {
      this.form.ruleInfoList.push({ type: 1, ladders: [{}, {}] })
    },
    // 移除时段规则
    removeLast(index) {
      this.form.ruleInfoList.splice(index,1)
    },
    // 获取星期类型
    getWeekTypeList() {
      getAllWeeks({}).then(response => {
        this.feeWeekList = response.data || []
      })
    },
    // 获取机构列表
    getDepartmentList() {
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.dialogFormType = 1
      this.$nextTick(() => {
        this.form = {
          ruleInfoList: [
            { type: 1, ladders: [{}, {}] }
          ]
        }
        this.$refs.form.clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogFormVisible = true
      this.dialogFormType = 2
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      getTempRule({ id: row.id }).then(response => {
        this.form = response.data || {}
      })
    },
    handleDelete(name, parkId) {
      this.$confirm(`您确定删除收费规则：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTempRule({ id: parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = {...this.form}
          form.ruleInfoList = form.ruleInfoList.map(item=>{
            let obj = { ...item }
            if(item.type == 2 || item.type == 1) delete obj.ladders
            if(item.type == 2){
              obj.crossCancelFirst = 0
              obj.freeMinutes = null
              obj.timeMaxAmount = null
            }
            return obj
          })
          if (this.dialogFormType === 1) {
            createTempRule(form).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
            })
          } else {
            updateTempRule(form).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .el-dynamic span {
    font-weight: 700;
    text-align: right;
  }

  .el-dynamic-block {
    display: flex;
  }

  .el-dynamic-span250{
   width: 250px;
  }
  .el-dynamic-span125{
    width: 125px;
    max-width: 330px;
  }

  .el-dynamic-span125{
    width: 125px;
    max-width: 330px;
  }

  .el-dynamic-block {
    display: block;
    margin-bottom: 5px;
  }

  .el-dynamic-block div.el-input {
    width: auto;
  }

  .el-dynamic-inline {
    display: inline-block;
  }

  .el-span-margin {
    margin: 14px;
  }
  .el-span-margin-right {
    margin-right: 75px;
  }
  .el-span-margin-left {
    margin-left: 20px;
  }

</style>
